package com.authine.cloudpivot.ext.service.impl;

import com.alibaba.cola.dto.SingleResponse;
import com.authine.cloudpivot.ext.constants.AppConst;
import com.authine.cloudpivot.ext.constants.ModelConst;
import com.authine.cloudpivot.ext.constants.PlatformConst;
import com.authine.cloudpivot.ext.model.order.OrderGoodsAcceptVO;
import com.authine.cloudpivot.ext.model.order.OrderGoodsReturnsVO;
import com.authine.cloudpivot.ext.dto.kingDee.request.KingDeeOrderGoodsReceived;
import com.authine.cloudpivot.ext.dto.kingDee.request.KingDeeOrderGoodsRefund;
import com.authine.cloudpivot.ext.dto.kingDee.request.KingDeeReturnGeneration;
import com.authine.cloudpivot.ext.dto.voucher.Voucher;
import com.authine.cloudpivot.ext.enums.kingdee.OrganizationRiseEnum;
import com.authine.cloudpivot.ext.enums.order.OrderGoodsStatusEnum;
import com.authine.cloudpivot.ext.service.OrderCreateVoucher;
import com.authine.cloudpivot.ext.service.OrderVoucherService;
import com.authine.cloudpivot.ext.utils.JdbcTemplateUtils;
import com.authine.cloudpivot.ext.utils.StringUtils;
import com.authine.mvp.app.launcher.domain.SelectorFormat;
import com.authine.mvp.app.launcher.utils.JsonParseObject;
import lombok.extern.slf4j.Slf4j;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

/**
 * @Author: liwei
 * @DateTime: 2021/8/12
 * @Description: TODO
 */

@Slf4j
public class OrderCreateVoucherImpl implements OrderCreateVoucher {

    OrderVoucherService orderVoucherService = new OrderVoucherService();

    /**
     *  收货生成凭证
     * @param orderGoodsAcceptDtoList 订单收货数据集合
     * @return 凭证数据集合
     */
    @Override
    public List<Voucher> receiveCreateVoucher(List<OrderGoodsAcceptVO> orderGoodsAcceptDtoList) {
        log.info("receiveCreateVoucher  request:{}", orderGoodsAcceptDtoList);
        List<Voucher> voucherList = new ArrayList<>();

        if (null == orderGoodsAcceptDtoList ||orderGoodsAcceptDtoList.isEmpty()) {
            log.info("未找到 订单收货记录信息！！！");
            return new ArrayList<>();
        }
        orderGoodsAcceptDtoList.stream().forEach(e->{

            String  orderCustomerGoodsId = e.getOrderCustomerGoodsId();
            String  orderVendorGoodsId = e.getOrderVendorGoodsId();

            //获取客户订单商品信息
            Map<String, Object> orderCustomerGoods = JdbcTemplateUtils.builder(ModelConst.T_ORDER_CUSTOMER_GOODS).selectField("*")
                    .eq("id", orderCustomerGoodsId).queryForMap();

            if (null == orderCustomerGoods){
                log.error("未找到 客户订单商品信息 ！！！");
                return;
            }
            //部门单选 需要转成别的格式  客户组织信息
            List<SelectorFormat> customerFormatList = new ArrayList<>();
            if(null != orderCustomerGoods.get("customer_organization_id")){
                customerFormatList = JsonParseObject.parseObject(String.valueOf(orderCustomerGoods.get("customer_organization_id")), SelectorFormat.class);
            }
            log.info("SelectorFormat :{}",customerFormatList);

            Map<String, Object> customerOrg = JdbcTemplateUtils.builder(AppConst.SYSTEM_MANAGEMENT, ModelConst.T_ORGANIZATION)
                    .eq("id", customerFormatList.get(0).getId()).selectField("*").queryForMap();

            if (null == customerOrg){
                log.error("未找到 客户组织信息 ！！！");
                return;
            }
            List<SelectorFormat> parentSelector = new ArrayList<>();
            if(null != customerOrg.get("parent_id")){
                log.info("parent_id :{}",customerOrg.get("parent_id"));
                parentSelector = JsonParseObject.parseObject((String) customerOrg.get("parent_id"), SelectorFormat.class);
            }
            log.info("parentSelector :{}",parentSelector);

            //t_order_vendor 获取供应商订单信息
            Map<String, Object> vendorOrder = JdbcTemplateUtils.builder(ModelConst.T_ORDER_VENDOR).eq("id", orderCustomerGoods.get("order_vendor_id"))
                    .selectField("*").queryForMap();

            if (null == vendorOrder){
                log.error("未找到 供应商订单数据 ！！！");
                return;
            }

            //部门单选 需要转成别的格式
            List<SelectorFormat> vendorFormatList = new ArrayList<>();
            if(null != vendorOrder.get("organization_id")){
                vendorFormatList = JsonParseObject.parseObject(String.valueOf(vendorOrder.get("organization_id")), SelectorFormat.class);
            }

            log.info("SelectorFormat :{}",vendorFormatList);

            Map<String, Object> vendorOrg = JdbcTemplateUtils.builder(AppConst.SYSTEM_MANAGEMENT, ModelConst.T_ORGANIZATION)
                    .eq("id", vendorFormatList.get(0).getId()).selectField("*").queryForMap();

            if (null == vendorOrg){
                log.error("未找到 供应商组织信息 ！！！");
                return;
            }

            //收货金额
            BigDecimal receiveAmount = BigDecimal.ZERO;
            //转采收货金额
            BigDecimal transferCostAmount = BigDecimal.ZERO;

            //商品未税单价
            BigDecimal pretaxPrice = new BigDecimal(String.valueOf(orderCustomerGoods.get("pretax_price")));

            //收货数量
            BigDecimal quantity = e.getQuantity();

            BigDecimal goodsQuantity = new BigDecimal(String.valueOf(orderCustomerGoods.get("quantity")));

            //是否虚拟供应商
            if (null == vendorOrg.get("virtual") || !Boolean.valueOf(String.valueOf(vendorOrg.get("virtual")))) {

                //注意： 这里 客户订单表 保存状态字段 存的是 字串
                OrderGoodsStatusEnum orderCustomerGoodsStatus = OrderGoodsStatusEnum.valueOf(String.valueOf(orderCustomerGoods.get("order_customer_goods_status")));

                //订单商品状态，若为已完成，则说明为最后一批收货
                if(orderCustomerGoodsStatus.equals(OrderGoodsStatusEnum.Done)){

                    //之前收货的数量
                    BigDecimal oldNum = goodsQuantity.subtract(quantity);
                    // 总金额
                    BigDecimal pretaxTotal = new BigDecimal(String.valueOf(orderCustomerGoods.get("pretax_total")));
                    //总金额 - 之前收货金额 = 当前收货金额
                    receiveAmount = pretaxTotal.subtract(pretaxPrice.multiply(oldNum).divide(BigDecimal.ONE,2, RoundingMode.HALF_UP));

                }else{

                    //此次商品收货（未税）金额
                    receiveAmount = pretaxPrice.multiply(quantity).divide(BigDecimal.ONE, 2, RoundingMode.HALF_UP);
                }

            }else{

                //注意 排序的问题
                Map<String,Object> param = new HashMap<>();
                param.put("order_customer_goods_id",orderCustomerGoodsId);
                String acceptTableName = JdbcTemplateUtils.getTableName(ModelConst.T_ORDER_GOODS_ACCEPT);
                StringBuilder sqlS = new StringBuilder("SELECT oa.* FROM ");
                sqlS.append(acceptTableName);
                sqlS.append("AS oa WHERE oa.order_customer_goods_id IN (:orderCustomerGoodsId) ORDER BY oa.id DESC");

                List<Map<String, Object>> acceptList = JdbcTemplateUtils.queryForList(sqlS.toString(), param);

                if (null == acceptList || acceptList.isEmpty()) {
                    log.error("未找到 订单商品收货 信息 ！！！");
                    return;
                }

                //收货记录总数量
                BigDecimal receivedNum = BigDecimal.ZERO;
                for (Map<String, Object> accept : acceptList) {
                    if (null != accept.get("quantity")) {

                        BigDecimal x = new BigDecimal(String.valueOf(accept.get("quantity")));
                        receivedNum = receivedNum.add(x);

                    }
                }

                //转采 根据采购批次分组
                //待付款 2，部分付款 3，已付款 4
                // 会员订单商品表 t_member_purchase_order_goods
                // 会员订单表 t_member_purchase_order
                // 转采订单商品表 t_transfer_order_goods
                // 转采订单表 t_transfer_order
                String memberOderTableName = JdbcTemplateUtils.getTableName(AppConst.ZHUANCAI,ModelConst.T_MEMBER_PURCHASE_ORDER);
                String memberOderGoodsTableName = JdbcTemplateUtils.getTableName(AppConst.ZHUANCAI,ModelConst.T_MEMBER_PURCHASE_ORDER_GOODS);
                String transferOrderTableName = JdbcTemplateUtils.getTableName(AppConst.ZHUANCAI,ModelConst.T_TRANSFER_ORDER);
                String transferOrderGoodsTableName = JdbcTemplateUtils.getTableName(AppConst.ZHUANCAI,ModelConst.T_TRANSFER_ORDER_GOODS);

                log.info("数据库名称  memberOderTableName:{},memberOderGoodsTableName:{},transferOrderTableName:{},transferOrderGoodsTableName:{}",memberOderTableName,memberOderGoodsTableName,transferOrderTableName,transferOrderGoodsTableName);

                StringBuilder sb = new StringBuilder();
                sb.append("SELECT  g.*  FROM ");
                sb.append(memberOderGoodsTableName);
                sb.append(" AS g LEFT JOIN ");
                sb.append(memberOderTableName);
                sb.append(" AS m ON m.id = g.member_purchase_order_id LEFT JOIN ");
                sb.append(transferOrderGoodsTableName);
                sb.append(" AS t ON t.id = g.transfer_order_goods_id LEFT JOIN ");
                sb.append(transferOrderTableName);
                sb.append(" AS o ON o.id = t.transfer_order_id WHERE o.order_type IS NULL AND m.is_rp <> TRUE AND m.member_purchase_order_status IN ( 2, 3, 4 ) AND t.cloud_order_goods_id = :orderGoodsId  ORDER BY g.purchase_batch ASC ");
                String sql = sb.toString();
                log.info("根据采购批次分组 执行SQL :{}",sql);
                Map<String,Object> paramM = new HashMap<>();
                paramM.put("orderGoodsId",orderCustomerGoodsId);
                List<Map<String, Object>> memberGoodsList = JdbcTemplateUtils.queryForList(sql, paramM);

                if (null == memberGoodsList || memberGoodsList.isEmpty()) {
                    log.error("未找到 转采订单相关数据 ！！！");
                    return;
                }

                //采购数量
                BigDecimal purchaseNum = BigDecimal.ZERO;
                //成本金额
                BigDecimal costAmount = BigDecimal.ZERO;
                //单次循环采购数量
                BigDecimal loopNum = BigDecimal.ZERO;

                BigDecimal quantityReceived = quantity;

                for (Map<String, Object> memberGoods : memberGoodsList) {

                    BigDecimal num = new BigDecimal(String.valueOf(memberGoods.get("num")));
                    purchaseNum = purchaseNum.add(num);

                    if (receivedNum.compareTo(loopNum = loopNum.add(num)) == 1) {
                        continue;
                    }

                    BigDecimal residueNum = loopNum.subtract(receivedNum);

                    if (quantityReceived.compareTo(residueNum) <=0) {

                        BigDecimal prePrice = new BigDecimal(String.valueOf(memberGoods.get("pre_price")));
                        costAmount = quantityReceived.multiply(prePrice).divide(BigDecimal.ONE,2, RoundingMode.HALF_UP).add(costAmount);
                        receivedNum = residueNum.add(receivedNum);
                        quantityReceived = quantityReceived.subtract(residueNum);
                    }
                }

                transferCostAmount = costAmount;
            }

            KingDeeOrderGoodsReceived kingDeeOrderGoodsReceived = new KingDeeOrderGoodsReceived();
            String customerName = String.valueOf(customerOrg.get("name"));
            kingDeeOrderGoodsReceived.setCustomerName(customerName);
            kingDeeOrderGoodsReceived.setParentCustomerName( parentSelector.isEmpty() || StringUtils.isBlank(parentSelector.get(0).getName()) ? customerName : parentSelector.get(0).getName());
            kingDeeOrderGoodsReceived.setCustomerOrderId(String.valueOf(orderCustomerGoods.get("order_customer_id")));
            kingDeeOrderGoodsReceived.setVirtual(Boolean.valueOf(String.valueOf(vendorOrg.get("virtual"))));
            kingDeeOrderGoodsReceived.setVendorId(String.valueOf(vendorOrg.get("id")));
            kingDeeOrderGoodsReceived.setVendorOrderId(String.valueOf(vendorOrder.get("id")));
            kingDeeOrderGoodsReceived.setOrgName(String.valueOf(vendorOrg.get("name")));
            kingDeeOrderGoodsReceived.setId(orderCustomerGoodsId);
            kingDeeOrderGoodsReceived.setPreAmount(receiveAmount);
            kingDeeOrderGoodsReceived.setPurchaseCostAmount(transferCostAmount);


            String account = "";
            if (PlatformConst.PLATFORM_ORGANIZATION_IDS.get(0).equals(customerFormatList.get(0).getId())) {
                account = OrganizationRiseEnum.GM.toString();
            }else if(PlatformConst.PLATFORM_ORGANIZATION_IDS.get(1).equals(customerFormatList.get(0).getId())){
                account = OrganizationRiseEnum.GM_HN.toString();
            }else{
                account = null;
            }

            kingDeeOrderGoodsReceived.setAccountName(account);

            List<KingDeeOrderGoodsReceived> kingDeeOrderGoodsReceivedList = new ArrayList<>();
            kingDeeOrderGoodsReceivedList.add(kingDeeOrderGoodsReceived);
            SingleResponse<List<Voucher>> response = orderVoucherService.receiptGoodsVoucher(kingDeeOrderGoodsReceivedList);

            if (null == response) {
                return;
            }

            voucherList.addAll(response.getData());
        });

        log.info("orderGoodsAcceptDtoList  业务逻辑处理结束 <<<");

        return voucherList;
    }



    @Override
    public void returnCreateVoucher(OrderGoodsReturnsVO orderGoodsReturnsDto, Boolean toPm) {

        log.info("returnCreateVoucher  request:{}", orderGoodsReturnsDto);
        if(null == orderGoodsReturnsDto || null == toPm){
            return;
        }

        //获取客户订单商品信息
        Map<String, Object> orderCustomerGoods = JdbcTemplateUtils.builder(ModelConst.T_ORDER_CUSTOMER_GOODS).selectField("*")
                                    .eq("id", orderGoodsReturnsDto.getOrderCustomerGoodsId()).queryForMap();

        if (null == orderCustomerGoods){
            log.error("未找到 客户订单商品信息 ！！！");
            return;
        }

        //收货数量获取 注意 排序的问题
        Map<String,Object> paramA = new HashMap<>();
        paramA.put("order_customer_goods_id",orderGoodsReturnsDto.getOrderCustomerGoodsId());
        String acceptTableName = JdbcTemplateUtils.getTableName(ModelConst.T_ORDER_GOODS_ACCEPT);
        StringBuilder sqlA = new StringBuilder("SELECT oa.* FROM ");
        sqlA.append(acceptTableName);
        sqlA.append("AS oa WHERE oa.order_customer_goods_id IN (:orderCustomerGoodsId) ORDER BY oa.id DESC");

        List<Map<String, Object>> acceptList = JdbcTemplateUtils.queryForList(sqlA.toString(), paramA);

        if (null == acceptList || acceptList.isEmpty()) {
            log.error("未找到 订单商品收货 信息 ！！！");
            return;
        }

        BigDecimal receivedNum = BigDecimal.ZERO;
        for (Map<String, Object> accept : acceptList) {
            if (null != accept.get("quantity")) {

                BigDecimal data = new BigDecimal(String.valueOf(accept.get("quantity")));
                receivedNum = receivedNum.add(data);

            }
        }

        Map<String,Object> paramR = new HashMap<>();
        paramA.put("order_customer_goods_id",orderGoodsReturnsDto.getOrderCustomerGoodsId());
        String returnsTableName = JdbcTemplateUtils.getTableName(ModelConst.T_ORDER_GOODS_RETURNS);
        StringBuilder sqlR = new StringBuilder("SELECT or.* FROM ");
        sqlR.append(returnsTableName);
        sqlR.append("AS or WHERE oa.order_customer_goods_id IN (:orderCustomerGoodsId) ORDER BY oa.id DESC");

        List<Map<String, Object>> returnList = JdbcTemplateUtils.queryForList(sqlR.toString(), paramR);

        if (null == returnList ||returnList.isEmpty()){
            log.error("未找到 订单退货相关数据 ！！！");
            return;
        }

        //已退数量
        BigDecimal returnNum = BigDecimal.ZERO;
        for (Map<String, Object> returns : returnList) {
            if (null != returns.get("quantity")) {

                BigDecimal data = new BigDecimal(String.valueOf(returns.get("quantity")));
                returnNum = returnNum.add(data);

            }
        }


        //已收数量中 可退 部分
        BigDecimal subtract = receivedNum.subtract(returnNum);

        //t_order_vendor 获取供应商订单信息
        Map<String, Object> vendorOrder = JdbcTemplateUtils.builder(ModelConst.T_ORDER_VENDOR).eq("id", orderCustomerGoods.get("order_vendor_id"))
                                            .selectField("*").queryForMap();

        if (null == vendorOrder){
            log.error("未找到 供应商订单数据 ！！！");
            return;
        }

        //部门单选 需要转成别的格式
        List<SelectorFormat> vendorFormatList = new ArrayList<>();
        if(null != vendorOrder.get("organization_id")){
            vendorFormatList = JsonParseObject.parseObject(String.valueOf(vendorOrder.get("organization_id")), SelectorFormat.class);
        }

        log.info("SelectorFormat :{}",vendorFormatList);

        //供应商组织信息
        Map<String, Object> vendorOrg = JdbcTemplateUtils.builder(AppConst.SYSTEM_MANAGEMENT, ModelConst.T_ORGANIZATION)
                                    .eq("id", vendorFormatList.get(0).getId()).selectField("*").queryForMap();

        if (null == vendorOrg){
            log.error("未找到 供应商组织信息 ！！！");
            return;
        }

        //退货金额
        BigDecimal returnAmount = BigDecimal.ZERO;
        //转采收货金额
        BigDecimal transferAmount = BigDecimal.ZERO;
        //本次退货数量
        BigDecimal quantity = orderGoodsReturnsDto.getQuantity();
        //可退部分存在
        if (subtract.compareTo(BigDecimal.ZERO) == 1) {

            //virtual 判断是否虚拟供应商
            if (null == vendorOrg.get("virtual") || !Boolean.valueOf(String.valueOf(vendorOrg.get("virtual")))) {

                //此次商品退货（未税）金额, 只计算退已收的部分
                BigDecimal num = subtract.compareTo(quantity) >= 0 ? quantity : quantity.subtract(subtract);

                BigDecimal pretaxPrice = new BigDecimal(String.valueOf(orderCustomerGoods.get("pretax_price")));

                OrderGoodsStatusEnum orderCustomerGoodsStatus = OrderGoodsStatusEnum.valueOf(String.valueOf(orderCustomerGoods.get("order_customer_goods_status")));

                //订单商品状态，若为已完成，则说明为最后一批收货
                if(orderCustomerGoodsStatus.equals(OrderGoodsStatusEnum.Done)){

                    BigDecimal orderNum = new BigDecimal(String.valueOf(orderCustomerGoods.get("quantity")));

                    BigDecimal num2 = orderNum.subtract(num);

                    BigDecimal pretaxTotal = new BigDecimal(String.valueOf(orderCustomerGoods.get("pretax_total")));

                    returnAmount = pretaxTotal.subtract(pretaxPrice.multiply(num2).divide(BigDecimal.ONE,2, RoundingMode.HALF_UP));

                }else{

                    returnAmount = pretaxPrice.multiply(num).divide(BigDecimal.ONE,2, RoundingMode.HALF_UP);

                }

            }else{

                //已经收货数量
                BigDecimal older = receivedNum.subtract(quantity);

                //转采 根据采购批次分组
                //待付款 2，部分付款 3，已付款 4
                // 会员订单商品表 t_member_purchase_order_goods
                // 会员订单表 t_member_purchase_order
                // 转采订单商品表 t_transfer_order_goods
                // 转采订单表 t_transfer_order
                String memberOderTableName = JdbcTemplateUtils.getTableName(AppConst.ZHUANCAI,ModelConst.T_MEMBER_PURCHASE_ORDER);
                String memberOderGoodsTableName = JdbcTemplateUtils.getTableName(AppConst.ZHUANCAI,ModelConst.T_MEMBER_PURCHASE_ORDER_GOODS);
                String transferOrderTableName = JdbcTemplateUtils.getTableName(AppConst.ZHUANCAI,ModelConst.T_TRANSFER_ORDER);
                String transferOrderGoodsTableName = JdbcTemplateUtils.getTableName(AppConst.ZHUANCAI,ModelConst.T_TRANSFER_ORDER_GOODS);

                log.info("数据库名称  memberOderTableName:{},memberOderGoodsTableName:{},transferOrderTableName:{},transferOrderGoodsTableName:{}",memberOderTableName,memberOderGoodsTableName,transferOrderTableName,transferOrderGoodsTableName);

                StringBuilder sb = new StringBuilder();
                sb.append("SELECT  g.*  FROM ");
                sb.append(memberOderGoodsTableName);
                sb.append(" AS g LEFT JOIN ");
                sb.append(memberOderTableName);
                sb.append(" AS m ON m.id = g.member_purchase_order_id LEFT JOIN ");
                sb.append(transferOrderGoodsTableName);
                sb.append(" AS t ON t.id = g.transfer_order_goods_id LEFT JOIN ");
                sb.append(transferOrderTableName);
                sb.append(" AS o ON o.id = t.transfer_order_id WHERE o.order_type IS NULL AND m.is_rp <> TRUE AND m.member_purchase_order_status IN ( 2, 3, 4 ) AND t.cloud_order_goods_id = :orderGoodsId  ORDER BY g.purchase_batch ASC ");
                String sql = sb.toString();
                Map<String,Object> param = new HashMap<>();
                param.put("orderGoodsId",orderGoodsReturnsDto.getOrderCustomerGoodsId());
                List<Map<String, Object>> memberGoodsList = JdbcTemplateUtils.queryForList(sql, param);

                if (null == memberGoodsList || memberGoodsList.isEmpty()) {
                    log.error("未找到 转采订单相关数据 ！！！");
                    return;
                }
                //采购数量
                BigDecimal purchaseNum = BigDecimal.ZERO;
                //成本金额
                BigDecimal costAmount = BigDecimal.ZERO;
                //单次循环采购数量
                BigDecimal loopNum = BigDecimal.ZERO;

                BigDecimal quantityReceived = quantity;

                for (Map<String, Object> memberGoods : memberGoodsList) {

                    BigDecimal num = new BigDecimal(String.valueOf(memberGoods.get("num")));
                    purchaseNum = purchaseNum.add(num);

                    if (receivedNum.compareTo(loopNum = loopNum.add(num)) == 1) {
                        continue;
                    }

                    BigDecimal residueNum = loopNum.subtract(receivedNum);

                    if (quantityReceived.compareTo(residueNum) <=0) {

                        BigDecimal prePrice = new BigDecimal(String.valueOf(memberGoods.get("pre_price")));
                        costAmount = quantityReceived.multiply(prePrice).divide(BigDecimal.ONE,2, RoundingMode.HALF_UP).add(costAmount);
                        receivedNum = residueNum.add(receivedNum);
                        quantityReceived = quantityReceived.subtract(residueNum);
                    }
                }

                transferAmount = costAmount;
            }
        }



        //获取退货组织id
        orderCustomerGoods.get("customer_organization_id");
        orderCustomerGoods.get("id");

        List<SelectorFormat> customerSelector = new ArrayList<>();
        if(null != orderCustomerGoods.get("organization_id")){

            customerSelector = JsonParseObject.parseObject(String.valueOf(orderCustomerGoods.get("organization_id")), SelectorFormat.class);
        }
        log.info("customerSelector :{}",customerSelector);

        //客户组织信息
        Map<String, Object> customerOrg = JdbcTemplateUtils.builder(AppConst.SYSTEM_MANAGEMENT, ModelConst.T_ORGANIZATION)
                .eq("id", customerSelector.get(0).getId()).selectField("*").queryForMap();

        List<SelectorFormat> parentSelector = new ArrayList<>();
        if(null != customerOrg.get("parent_id")){

            parentSelector = JsonParseObject.parseObject(String.valueOf(customerOrg.get("parent_id")), SelectorFormat.class);
        }
        log.info("parentSelector :{}",parentSelector);


        List<SelectorFormat> platformSelector = new ArrayList<>();
        if(null != customerOrg.get("platform_id")){

            platformSelector = JsonParseObject.parseObject(String.valueOf(customerOrg.get("platform_id")), SelectorFormat.class);
        }
        log.info("platformSelector :{}",platformSelector);


        KingDeeOrderGoodsRefund refund = KingDeeOrderGoodsRefund.builder()
                                            .id(orderGoodsReturnsDto.getOrderCustomerGoodsId())
                                            .vendorId(String.valueOf(vendorOrg.get("id")))
                                            .vendorOrderId(String.valueOf(vendorOrder.get("id")))
                                            .vendorName(String.valueOf(vendorOrg.get("name")))
                                            .virtual(Boolean.valueOf(String.valueOf(vendorOrg.get("virtual"))))
                                            .purchaseAmount(transferAmount)
                                            .goodsAmount(returnAmount)
                                            .customerOrderId(String.valueOf(orderCustomerGoods.get("order_customer_id")))
                                            .customerOrgName(String.valueOf(customerOrg.get("name")))
                                            .parentCustomerOrgName(parentSelector.get(0).getName()).build();

        //退货生成凭证
        log.warn("退货生成凭证：转采金额{}，平台金额{}", transferAmount, returnAmount);

        if(transferAmount.compareTo(BigDecimal.ZERO) != 0 || returnAmount.compareTo(BigDecimal.ZERO) != 0){

            String account = "";
            if (PlatformConst.PLATFORM_ORGANIZATION_IDS.get(0).equals(platformSelector.get(0).getId())) {
                account = OrganizationRiseEnum.GM.toString();
            }else if(PlatformConst.PLATFORM_ORGANIZATION_IDS.get(1).equals(platformSelector.get(0).getId())){
                account = OrganizationRiseEnum.GM_HN.toString();
            }else{
                account = null;
            }

            KingDeeReturnGeneration kingDeeReturnGeneration = new KingDeeReturnGeneration(refund, toPm, account);

            orderVoucherService.returnGoodsVoucher(kingDeeReturnGeneration);
        }

        log.info("returnCreateVoucher  业务逻辑处理结束 <<<");

    }

}
